<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="查询日期范围" label-width="120" prop="datepicker">
        <el-date-picker
          v-model="datepicker"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="单据号" prop="orderId">
        <el-input placeholder="请输入单据号" v-model="queryParams.orderId"/>
      </el-form-item>
      <!--      <el-form-item label="工厂名称" prop="businessId" v-hasRole="['spurAdmin']">-->
      <!--        <el-select v-model="queryParams.businessId" placeholder="请选择工厂名称" clearable @keyup.enter.native="handleQuery">-->
      <!--          <el-option-->
      <!--            v-for="item in factoryNameOptions"-->
      <!--            :key="item.value"-->
      <!--            :label="item.label"-->
      <!--            :value="item.value"/>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="单据状态" prop="flag">
        <el-select v-model="queryParams.flag" placeholder="请选择单据状态" clearable @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in orderStateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :disabled="multiple"
          v-hasPermi="['document:relation:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="relationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="任务编号" align="center" prop="relationId"/>
      <el-table-column label="药品名称" align="center" prop="productName"/>
      <el-table-column label="药品子类编码" align="center" prop="typeNo"/>
      <el-table-column label="包装比例" align="center" prop="pkgRatio"/>
      <el-table-column label="提交人" align="center" prop="nickName"/>
      <el-table-column label="完成时间" align="center" prop="actDate"/>
      <el-table-column label="操作" align="center" width="180px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleView(scope.row)"
            v-hasPermi="['document:relation:list']"
          >查看详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleExport(scope.row)"
            v-hasPermi="['document:relation:export']"
          >导出
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zhongzuo-copy"
            v-if="scope.row.orderState === '0'"
            @click="handleDelete(scope.row)"
            v-hasPermi="['document:relation:remove']"
          >重做
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-drawer
      :title="title"
      :visible.sync="table"
      direction="btt"
      size="80%">
      <el-table :data="gridData">
        <el-table-column property="curCode" label="追溯码"/>

        <el-table-column property="packLayer" label="包装层级"/>
        <el-table-column property="parentCode" label="父码">
          <template slot-scope="scope">
            <label v-if="scope.row.parentCode === '0'">
              无
            </label>
            <label v-else>
              {{ scope.row.parentCode }}
            </label>
          </template>
        </el-table-column>
        <el-table-column property="batchNo" label="生产批号"/>
        <el-table-column property="madeDate" label="生产日期"/>
        <el-table-column property="validateDate" label="有效期至"/>
        <el-table-column property="actDate" label="扫描时间" :formatter="formatDate"/>
        <el-table-column property="flag" label="码状态">
          <template slot-scope="scope">
            <label v-if="scope.row.flag === '0'">
              正常
            </label>
            <label v-else-if="scope.row.flag === '1'">
              拼箱
            </label>
            <label v-else-if="scope.row.flag === '2'">
              零箱
            </label>
            <label v-else-if="scope.row.flag === '3'">
              既拼箱又零箱
            </label>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="codeTotal>0"
        :total="codeTotal"
        :page.sync="indexUse.pageNum"
        :page-sizes="[30,50,70,100]"
        :limit.sync="indexUse.pageSize"
        @pagination="handleSizeChange"
      />
    </el-drawer>

  </div>
</template>
<style lang="scss">
.my-label {
  background: #E1F3D8;
}
</style>
<script>
import {queryRelationList, getRelationCode, getRelationXml, deleteRelation} from "@/api/document/relation";
// import {Fusion_Manufacturer_Info} from "@/api/documentProcess/warehouseoutorin";

export default {
  name: "List",
  // dicts: ['audit_status', 'task_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 查看详情弹出层是否显示
      table: false,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //追溯码总条数
      codeTotal: 0,
      // 弹出层标题
      title: "",
      // 是否弹出任务详情
      isShow: false,
      //表格列表
      relationList: [],
      //工厂列表
      factoryNameOptions: [],
      //追溯码列表
      relationCodeList: [],
      // 追溯码详情
      gridData: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        businessId: '',
        beginDate: '',
        endDate: '',
        flag: '',
        orderId: ''
      },
      // 日期选择框
      datepicker: null,
      //页面分页显示追溯码用
      indexUse: {
        pageNum: 1,
        pageSize: 30,
      },
      // 表单参数
      form: {},
      // 详情数据
      detail: {},
      // 表单校验
      orderStateOptions: [{label: "未导出", value: '0'},
        {label: '已导出', value: '1'}]
    };
  },
  created() {
    this.getList();
    // this.getFactoryList()
  },
  methods: {

    /** 查询生产任务列表 */
    getList() {
      this.loading = true;
      let date = this.datepicker;
      if (date !== null && typeof date !== "undefined") {
        let startTime = date[0];
        let endTime = date[1];

        this.queryParams.beginDate = startTime;
        this.queryParams.endDate = endTime;
      }
      queryRelationList(this.queryParams).then(response => {
        this.relationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /**
     * 查询工厂信息列表
     */
    // getFactoryList() {
    //   Fusion_Manufacturer_Info().then(response => {
    //     this.factoryNameOptions = response.data;
    //   });
    // },

    /** 查看追溯码详情 */
    handleView(row) {
      this.relationCodeList = [];
      this.codeTotal = 0;
      this.title = "任务编号为: " + row.relationId + " 的追溯码详情"
      // 查询参数
      const params = {
        relationId: row.relationId,
        typeNo: row.typeNo,
        entId: row.entId
      }
      getRelationCode(params).then(response => {
        this.relationCodeList = response.data;
        this.codeTotal = response.data.length
        this.handleSizeChange();
        this.table = true;
      });
    },

    // 表单重置
    reset() {
      this.form = {
        LineID: null,
      };
      this.resetForm("form");
    },

    // 多选框发生改变触发
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.relationId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery();
    },

    /** 导出关联关系文件 */
    handleExport(row) {
      const relationId = row.relationId || this.ids;
      this.$modal.confirm('是否确认导出任务编号为"' + relationId + '"的关联关系文件?').then(() => {
        return getRelationXml(relationId);
      }).then(response => {
        let msg = "";
        const files = response.data || [];
        const batchSize = 10;
        const totalFiles = files.length;

        const batchDownload = (start, end) => {
          for (let i = start; i < end && i < totalFiles; i++) {
            const item = files[i];
            let index = 0;
            Object.keys(item).forEach(key => {
              const id = key; // 获取键（ID）
              const xmlData = item[key]; // 获取值（XML数据）
              // 在这里可以对xmlData进行处理，比如下载XML文件
              if (!xmlData.startsWith("error:")) {
                const blob = new Blob([xmlData], {type: 'text/xml'});
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `${id}.xml`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
              } else {
                if (index > 0) {
                  msg = msg + "文件名为:<strong>" + id + "</strong>导出失败！失败原因:" + "<strong>" + xmlData + "</strong><br>"
                  index++;
                } else {
                  msg = msg + "文件名为:<strong>" + id + "</strong>导出失败！失败原因:" + "<strong>" + xmlData + "</strong>"
                  index++;
                }
              }
            });
          }

          // 下载完成后等待1秒
          if (end < totalFiles) {
            setTimeout(() => {
              const nextStart = end;
              const nextEnd = Math.min(nextStart + batchSize, totalFiles);
              batchDownload(nextStart, nextEnd);
            }, 1000);
          }
        };

        batchDownload(0, Math.min(batchSize, totalFiles));

        if (msg !== "") {
          this.$message({
            dangerouslyUseHTMLString: true,
            message: msg,
            type: "warning",
            duration: 5000,
          });
        }
        this.getList();
      }).catch(() => {
        // 错误处理
      });
    },

    /** 前端页面分页操作 */
    handleSizeChange() {
      this.gridData = []
      this.loading = true;
      const startIndex = (this.indexUse.pageNum - 1) * this.indexUse.pageSize;
      const endIndex = startIndex + this.indexUse.pageSize;
      // 获取当前页的数据relationCodeListShow
      this.gridData = this.relationCodeList.slice(startIndex, endIndex);
      this.loading = false;
    },


    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认重做任务编号为"' + row.relationId + '"的单据?').then(function () {
        return deleteRelation(row.relationId);
      }).then(() => {
        this.getList();
        this.$message({
          message: "删除成功",
          type: "success",
        });
      }).catch(() => {
      });
    },

    /** 格式化日期 */
    formatDate(row, column, cellValue, index) {
      const daterc = row[column.property]
      if (daterc == null || daterc === "") return "";
      const date = new Date(daterc);
      const year = date.getFullYear();
      const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
      const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
      const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
    },
  }
};

</script>

